import json
import httpx
from typing import Any
import os
from dotenv import load_dotenv
load_dotenv()
# 汽车入厂API配置
CAR_ENTER = os.getenv("BASEA_CAR_URL", "") + "/prl-Report/web/homePage/findHomeQuantityPrice"
CAR_COOKIE = os.getenv("FUEL_TOKEN", "")

async def find_home_quantity_price(startTime: str, endTime: str) -> dict[str, Any] | None:
    payload = {
        "startTime": startTime,
        "endTime": endTime,
        "type": 1
    }
    headers = {
        "Content-Type": "application/json"
    }
    async with httpx.AsyncClient() as client:
        try:
            client.cookies.set('jreapSid', CAR_COOKIE)
            response = await client.get(CAR_ENTER, params=payload, headers=headers, timeout=30.0)
            response.raise_for_status()
            return response.json()
        except httpx.HTTPStatusError as e:
            return {"error": f"HTTP 错误: {e.response.status_code}"}
        except Exception as e:
            return {"error": f"请求失败: {str(e)}"}

def format_quantity_price(data: dict[str, Any] | Any) -> str:
    if isinstance(data, str):
        try:
            data = json.loads(data)
        except Exception as e:
            return f"无法解析煤场量质价数据: {e}"
    if data.get("flag") == "error":
        return f"⚠️ {data['msg']}"
    resultList = data.get("result", [])
    quantity_price_info = []
    for item in resultList:
        coal_area_name = item.get("coalAreaName", "未知")
        in_stock_quantity = item.get("inStockQuantity", "未知")
        out_bound_volume = item.get("outBoundVolume", "未知")
        inventory = item.get("inventory", "未知")
        quantity_price_info.append(f"煤场名称: {coal_area_name}, 入库量: {in_stock_quantity}, 出库量: {out_bound_volume}, 库存量: {inventory}")
    quantity_price_info_str = "; ".join(quantity_price_info)
    return (
        f"{quantity_price_info_str}"
    )